
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

/**
 * @author by mozping
 * @Classname FileUtils
 * @Description TODO
 * @Date 2019/1/18 16:18
 */
public class FileUtils {

    /**
     * 获取文件行数
     */
    public static int getLinesOfFile(String filePath) throws IOException {
        File file = new File(filePath);
        if (file.isFile() && file.exists() && file.canRead()) {
            FileReader fr = new FileReader(file);
            LineNumberReader lnr = new LineNumberReader(fr);
            int linenumber = 0;
            while (lnr.readLine() != null) {
                linenumber++;
            }
            lnr.close();
            System.out.println("文件" + file.getAbsolutePath() + "行数是:" + linenumber);
            return linenumber;
        }
        return 0;
    }


    /**
     * 获取文件夹下面所有文件行数
     */
    public static int getLinesOfFile(String foldName, boolean needRecursion) throws IOException {
        File fn = new File(foldName);
        int totalLine = 0;
        if (fn.isDirectory()) {
            File[] files = fn.listFiles();
            for (File f : files) {
                if (f.isFile()) {
                    totalLine += getLinesOfFile(f.getAbsolutePath());
                }
                if (f.isDirectory() && needRecursion) {
                    totalLine += getLinesOfFile(f.getAbsolutePath(), true);
                }
            }
        }
        return totalLine;
    }
}
